Central Article

Creating Offline Web Applications in Macromedia Central

Geoffrey "gSOLO" Williams

Geoffrey Williams - Will Flash For Food ™
Personal Weblog

Macromedia Central addresses a variety of needs for many Flash application developers. It works in environments where a connection to the Internet or network is not always be available. Consumers increasingly use mobile devices and applications, and Macromedia has followed suit. Central provides new application functionality that takes advantage of your user's network status by providing cache files for offline use and by detecting and responding to changes in a user's connection status. With the growing use of occasionally connected devices, the advantages and benefits of using connection-aware applications are many.

This article explains how Central can help you create applications that work in both offline and online environments. I will discuss some of the key elements in creating Central applications. In the last half of the article, I will explain how you can build a simple Central application that uses its caching capabilities for offline environments.

Requirements

These examples assume that you have a basic understanding of how the Macromedia Central workflow works. This includes how to set up your development environment and how to test, develop, and debug an application. Read Mike Chambers' Macromedia Central Development Quick Start Guide if you aren't familiar with these basics. To complete this tutorial, you must have or install the following software and files:

A web server (on your local machine or at a web host)

 

Macromedia Central

Install Central now (free) ›

Macromedia Central SDK

Download it now ›

Macromedia Flash MX 2004


Tutorials and sample files:


Productivity is one benefit of using a connection-aware application. When users can still reference, analyze, and manipulate network data when no live network connection is available, they can work more efficiently. Convenience is another advantage. With current network-dependent applications, if a user loses a connection, the application stops working. If you make a portion of the data available offline to your user instead, it prevents the user from having to find a local hot spot to continue his/her business.

Consumers are already using occasionally connected devices. Several of these devices are already Flash Player-enabled; in turn, you can install and run Macromedia Central on these devices. The most notable occasionally connected device is the notebook computer. Although desktop computers still outsell Notebooks, Notebooks are on the rise; the entry-level price for getting a decent notebook computer is falling. With more powerful chipsets, longer battery life, and built-in wireless modems, notebooks have gained ground in the wired-desktop arena. With wireless access points and other unwired technologies, users can easily roam in and out of connected areas. PDAs, mobile phones, and other mobile devices are developing in similar ways, raising the awareness of web and desktop application developers.

How Central Uses Connection Awareness

Macromedia Central can recognize a user's connection status in two ways. In one method, when a user switches his/her connection state, it calls an event handler; in your application, you can call a method at any time to retrieve the current connection status. Well-designed applications use this connection awareness to create a seamless online and offline experience for users.

Note: Remember that users communicate their connection status to Central; Central cannot determine connection status directly. By selecting the lightning bolt in the Central toolbar, users can toggle between online and offline mode.

To set up your applications for connection awareness, use the following event handlers and functions in your ActionScript logic.

The onNetworkChange Shell, Agent, and Console Event Handler

The shell, agent, and console event handler onNetworkChange alerts your application that the user has made changes to his connection to the Internet or network. Keep in mind that Macromedia Central does not detect if there is an Internet connection present; rather, it relies on user interaction to transmit its state. Central calls the onNetworkChange handler and passes a Boolean value as an argument indicating the new connection status.

Example:
	
function onNetworkChange(connected) 
{
	gOnline = connected;
	if (gOnline)
	{		
          	updateData();
	}
}

The isConnected Function

Use the isConnected function to determine Central's connection status during any step within your ActionScript logic. As a method of the AgentManager, Shell, or Console, isConnected returns a boolean value of true if the user is connected and false if the user is offline. Because the onNetworkChange event handler is only called when the user's online status changes, it is important to call the event handler when initializing your application to transmit the current connection state. This prevents you from having to write isConnected calls throughout your application; likewise, you can consolidate your connection management in the onNetworkChange event.

Example:

function onActivate(shell) 
{
	/* set a variable to reference the AgentManager, Shell, or Console */
	gShell = shell;

	/* take current state and trigger onNetworkChange */
	onNetworkChange( gShell.isConnected() );

Caching Files and Data on the Client Machine

Caching files and data in Macromedia Central is a large part of making your applications work offline. There are three methods to caching files for offline use.

You can include arbitrary files that Central will download when users install your application, and you can use local shared objects. Macromedia Central also includes APIs that let you simply specify a URL of a file to store on your users’ local machines. After you've cached data locally with any of these methods, Flash Player in Central looks in the cache first to retrieve data with any of the ActionScript commands for retrieving remote data, such as the loadMovie and loadVariables commands. You can cache most file types, but there are some files that are considered unsafe that you cannot cache on users’ machines. These file types include: .ad, .hlp, .msi, .vb, .adp, .hta, .msp, .vbe, .asp, .inf, .mst, .vbs, .bas, .ins, .pcd, .vsd, .bat, .isp, .pif, .vss, .chm, .jsp, .reg, .vst, .cmd, .jse, .scr, .vsw, .com, .lnk, .sct, .ws, .cpl, .mdb, .shb, .wsc, .crt, .mde, .shs, .wsf, .exe, .msc, .url, and .wsh.

For security reasons, you cannot use getURL to open cached local Internet files. The getURL calls will try to open users' default browsers and download the file from the web server. You may instruct users on the location of the cached files so they can open and execute them, but this method is not recommended. In its current iteration, use caching for files that Flash Player can use and or display.

Central stores cached files in the following locations:

  • Windows 2000 and XP: C:\Documents & Settings\<userName>\Application Data\ Macromedia\Central\Local Internet\<domainName.com>
  • Windows Win 98 and ME: C:\WINDOWS\Application Data\Macromedia\Central\ Local Internet\<domainName.com>
  • Macintosh: HardDisk:Users: <userName>:Library:Application Support:Macromedia:Central: Local Internet:<domainName.com>

The product.xml file and file Tag

The product.xml file is the XML descriptor file for your product. The product.xml file describes your product, including all of the applications and their associated components, pods, and agents. Find more information about the product.xml file in the Macromedia Central SDK.

Use a child element of an Application tag, the file tag, to specify additional files that Central will install along with your application. Installing files locally gives your application faster access to the files and lets users access the files when Central is offline. This tag stores files under the Central directory, along with any of the other essential application files. The file tag has a src attribute that specifies the source of the cached file. The src attribute can either be an absolute or relative URL.

<file src="/directory/myImage.jpg"/>	
<file src="http://www.domain.com/directory/myStrings.txt"/>

When you cache files, they should be downloaded from the same domain as the application, otherwise the user will receive an error and the application will not install. Macromedia Central cannot discern separate hosts within the same domain. For example; http://www.domain.com/file.swf would overwrite http://sub.domain.com/file.swf.

Note: The size limit of a cached file is 20MB. During your application installation, if one or more of the files are over 20MB, Central will not download the oversized file, and the user will receive an error indicating some files did not download.

The addToLocalInternetCache Method

New in Macromedia Central is the ability to use built-in APIs for caching data for offline use. There are three methods for managing cached files on users’ machines: addToLocalInternetCache, inLocalInternetCache, and removeFromLocalInternetCache. These methods are all available within the scope of the AgentManager, Shell, or Console.

Use addToLocalInternetCache(arguments are: strUrl, bOverwrite, and expiration) to add data to the local cache. The strUrl argument specifies the absolute URL of the file that you wish to cache. The other arguments are optional and help you manage the updates and duration the files in cache. The bOverwrite argument is a boolean value that specifies true if data from the URL can overwrite the cached data; or false, if the data is already in the cache and the data from the URL cannot overwrite the file. The expiration argument can be either a date object (specifying a date when Central will remove the file from the local cache) or a number (specifying how many days the file will stay in cache). No special techniques are necessary to access cached data. It is important to realize that these types of methods will always retrieve data from the cache if it is available. To get new data from the Internet, you must either delete the data from the cache with the removeFromLocalInternetCache(strUrl) method, which removes the specified data out of the cache, or replace it by setting the bOverwrite parameter of the addToLocalInternetCache method to true.

I recommend using inLocalInternetCache(strUrl) to check whether a prior call to addToLocalInternetCache was successful and whether a URL's asset is currently in the cache. This method returns a true or false.

Use ObjectName.removeFromLocalInternetCache(strUrl) to remove a URL's asset from the local Internet cache. For example:

	/* this example adds a jpg to the cache, loads it, then checks if successful */
onActivate=function(shell)
{
     /* set a variable to reference the AgentManager, Shell, or Console */
     gShell=shell;

     var theFile="http://www.mysite.com/images/photo.jpg"
     // add it to the cache
     gShell.addToLocalInternetCache(theFile);
     someClipInstance.loadMovie(theFile);

     // check that the disk quota wasn't exceeded
     if(gShell.inLocalInternetCache(theFile) != true)
     {
          /* trigger homemade function to explain the image wasn't downloaded */
          myAlertFunction("The photo won't be available when offline");
     }

};

Note: In Central Preferences, the user sets the size limit for the cache that stores data. The default size is 20MB and all Central applications share that space. The expiration argument is optional and can be either a date object or an integer. If you specify this argument, Central removes cached data from the cache on the date specified in a date object or after the number of days specified by an integer. Also, when a user uninstalls or updates an application, Central removes any cache that the application created.

Local Shared Objects

Since Macromedia Central is built on top of Flash Player 6, it can take advantage of local shared objects just as any recently published Flash movie can. Shared objects are useful when storing results from web services, user preferences, or other parsed data. To ensure that your objects have unique names, include your application's unique application ID in the name of the local shared object. When Central calls its onActivate event handler, it passes the unique ID to your application.

	Example:

	function onActivate(shell, id)
	{
   		theName = "sharedObj" + id;
   		_so = SharedObject.getLocal(theName)
	}

Macromedia Central does not remove local shared objects from the user's machine when the user uninstalls an application. It is up to the developer to clean out any local shared objects for an application when a user uninstalls the application. Central, based on the Flash Player 6, does not have the SharedObject.clear method available to clear local shared objects like Flash Player 7. You can overcome this by implementing the following code, which removes the local shared object from the users' machines when they uninstall the application.

  Example:
    function onUninstall()
    {
        for(var value in _so.data)
           {
             delete _so.data[value];
           }
    }

One final note about local shared objects in Macromedia Central: Not all elements of your movie will be from the same domain. When a user wants to adjust the local storage settings for your application or if you use the System.showSettings function to display these settings, an undesired settings dialog message might appear for the user. If the current focus of the Central application is on an element that is from the macromedia.com domain like the Central components, for example, the settings dialog will display information for that domain and not the domain of your application. To fix this issue, set the focus to one of the elements of your application that is from your domain before a request, to show the settings dialog is made.

Example:
    function onSomeEvent() 
    {
         Selection.setFocus(this);
         System.showSettings(1);
    }
			

Building a Central Application

If you haven't already done so, download and install the software in the Software Requirements section at the beginning of this article.

Creating an Interface

The example application will let you specify a file URL and cache it for offline use. When users are in offline mode, they will then be able to view, browse, and manage the caching of these files. First I'll walk through creating interface elements.

  1. Create a new fla and save it as offline_files; set your publish settings for Flash Player 6.
  2. Place an MComboBox and two MIconButtons in the upper left corner of the stage, with instance names url_cbx, add_btn, and ctrl_btn. The combobox will hold the file names of currently cached files; it will also let you to enter a URL to preview a file. The first icon button will let you add or remove the specified file from the cache, while the second icon button will allow you to preview the file without adding it to cache (as well as start and stop any sounds). This won't be a pretty interface, just a functional one that illustrates the concept of caching files for offline use.

That’s it for the interface, the rest you’ll create dynamically.

Initiating the Application

Define a function that initiates the local shared object. The shared object includes two Central DataProviders that will hold information about the files that are in the local cache and items waiting to be stored in the local cache. Put all code on the first frame of the main Timeline.

// Connect to local shared object (LSO)
var _so = SharedObject.getLocal("cachecentral", "/");

/* Create a function that is called once our application has been initiated in the Central Shell */
function initCache() {

	// Create a quick reference to the data object of the LSO
	var cache = _so.data;

	// Do this once
	if (!cache.init) {
		cache.init = true;

		/* This will hold urls of files that are waiting to be put into the local cache */
		cache._offlineQueue = new Central.DataProviderClass();

		/* This is our data provider that lists all of the files that we have available for offline viewing; used to populate the combo box */
		cache._dataProvider = new Central.DataProviderClass();
	}

	_que = cache._offlineQueue;
	_dp = cache._dataProvider;

	// Populate the combo box with a list of cached files
	url_cbx.setDataProvider(_dp);

}

Simple enough, right? The next bit of initiation code that you add lets you display the text or an image, or play a sound from the cache.

/* Create a function that is called once our application has been initiated in the Central Shell */
function initDisplay() {
    var ypos = url_cbx._y + 37;
	
	// Create an empty MovieClip and TextField and position them on the stage
	this.createEmptyMovieClip("_mc", 100);
	_mc._x = 15;
	_mc._y = ypos;
	
	this.createTextField("_txt", 101, 15, ypos, 500, 400);
	_txt.wordWrap = _txt.multiline = true;
	
	// Create a Sound object for playing back MP3s
	_sound = new Sound(this);
}

I'll explain the final bit of initiation code at the very end. This includes the onActivate function, which creates a reference to the Central Shell.

Implementing Network Status

Now create the onNetworkStatus function, which will let your application download and cache files the user requested that were not available offline.

// Handle network status changes
function onNetworkChange(c) {
	
	/* Check connection; if connected, cache files that are waiting in the queue */
	if (c) {
		
		var total = _que.getLength();
		for (var i = 0; i < total; i++) {
			var u = _que.getItemAt(i).label;
			appShell.addToLocalInternetCache(u);
			_dp.addItem(u);
		}
		
		// Clear the queue
		_que.replaceAllItems(null);
	}
}

Adding Functionality with Application Controls

Now you will add some functionality to UI elements, starting with the display function. You will use this functionality to display the image or file, or play the MP3 specified in the URL in the combo box.

// Display or play the specified file
function display(u) {
	
	if (!appShell.inLocalInternetCache(u) && !appShell.isConnected()) {
		u = u_pfx + "/noimage.gif";
	}
	/* Figure out what type of file we will be presenting and proceed accordingly */
	var ext = u.substr(u.lastIndexOf("."), u.length);
	if (ext == ".gif" || ext == ".jpg" || ext == ".swf") {
		_mc.loadMovie(u);
		_mc._visible = true;
		_txt._visible = false;
	} else if (ext == ".mp3") {
		_sound.loadSound(u, true);
		_mc._visible = false;
		_txt._visible = false;
	} else {
		var _lv = new LoadVars();
		_lv.onLoad = function(s) {
			delete this.onLoad;
			_txt.text = unescape(this);
		};
		_lv.load(u);
		_mc._visible = false;
		_txt._visible = true;
	}
}

The following functionality controls adding and removing files from cache. Initiate this functionality by clicking the add_btn icon button that you placed on the Stage earlier.

// Add or Remove items from the cache
add_btn.onRelease = function() {
	var u = url_cbx.getValue();
	
	/* If the specified file is currently in the cache, remove it from the cache as well as the LSO */
	if (appShell.inLocalInternetCache(u) && !inQueue(u)) {
		appShell.removeFromLocalInternetCache(u);
		var total = _dp.getLength();
		for (var i = 0; i < total; i++) {
			if (_dp.getItemAt(i).label == u) {
				_dp.removeItemAt(i);
			}
		}
	
	// Cache the specified file if it is not currently cached
	} else {
		
		/* If we have an internet connection, we can add the file to the cache right away; if not, we add the url of the file to the queue */
		if (appShell.isConnected()) {
			appShell.addToLocalInternetCache(u);
			_dp.addItem(u);
		} else {
			_que.addItem(u);
			
			/* Display a generic image identifying that the file is in the queue, waiting to be downloaded */
			display("noimage.gif");
		}
		
	}
};

The next three sections of code define the change handler of the URL combo box and change the UI based on the value in the combo box. It also adds functionality to the control button, which starts and stops a sound, so that it doesn't play all the way through. Lastly, the code adds functionality to determine if a file is in the queue, as in the onRelease function above.

// Define the url combo box change handler
url_cbx.setChangeHandler("url_change"); 
function url_change() {
	
	// Store the value of the url combo box
	var u = url_cbx.getValue();
	
	// Reset the icon of the add / remove button
	if (appShell.inLocalInternetCache(u)) {
		add_btn.setIcon("icon_bookmark_remove");
	} else {
		add_btn.setIcon("icon_bookmark_add");
	}
	
	// Display or play the currently selected item
	display(u);
}

// Sound control button
ctrl_btn.onRelease = function() {
	if (_sound.position) {
		_sound.stop();
	} else {
		_sound.start();
	}
};

// Check if file is in the queue
function inQueue(u) {
	var total = _que.getLength();
	for (var i = 0; i < total; i++) {
		if (_que.getItemAt(i).label == u) {
			return true;
		}
	}
}

Final Initiation

In the final bits of ActionScript, initiate a few more functions. You must let the Central Shell know that this is a Central application, which exposes your app to the Central API. You must also set up the initial states of the interface objects.

// initiate
function onActivate(shell) {
	appShell = shell;
	onNetworkChange(appShell.isConnected());
	url_cbx.setEditable(true);
	ctrl_btn.setIcon("icon_alert");
	u_pfx = _url.substr(0, _url.lastIndexOf("/"));
	initDisplay();
	initCache();
}
function onDeactivate() {
	// Save the LSO
	_so.flush();
}
Central.initApplication(this, this);

product.xml and Installation

In the display function above, you may have noticed a reference to load noimage.gif when the Central Shell is offline and asks for a URL to cache or display. You're going to cache this image when a user installs your application, so that regardless of the user's connection status, your application will always be able to load the image. Using the file tag and src attribute in the product.xml so that Central knows to cache the file when it installs your app. The example source on the first page of the article includes the noimage.gif file. Open up Notepad or any text editor and save it as product.xml. I have pasted the XML file contents below, bolding the relevant portions.

<product name="Cache Central"
    created="1/22/2004"
    version="1"
    price="Free"
    category="Other"
    productID="CND100-063933-197221-612499">
    <author name="Geoffrey Williams" info="http://www.gsolo.com/blog"/>
    <description>Cache Files</description>  
  
    <application name="Cache Central"
    src="offline_files.swf"
    width="620" height="500"
    lang="en"
    background="#FFFFFF"
    version="1">

    	<file src="noimage.gif"/>

    </application>

</product>

Now you must put the applicable files on a web server and install your application.

  1. Place the files product.xml, noimage.gif, and offline_files.swf in a directory on your web server.
  2. Start Central and look at what you created.
  3. To install the application, go to the file menu and select Install Application from URL…
  4. Enter in the path to your product.xml file on your server and click Install.

Testing Your Central Application

This example app has some flaws, as I have not added some checking scenarios that might arise—but go ahead and test it anyway. Start with the product.xml file.

  1. Type the URL of the product.xml file in the URL combo box and click Enter. Does the beginning of the XML appear underneath the combo box?

    Testing the XML file.

    Figure 1. Testing the XML file

  2. Switch Central to offline mode. With the URL of your product.xml still in the combo box click the Add button. The "file not available" image appears.

    Your application in the offline mode.

    Figure 2. Your application in the offline mode

  3. Switch back to online mode. Central adds the file to your cache. Select the file from the combo box. It will appear as it did before.
  4. Switch back to offline mode and select the file. Your application will display the cached file where it previously displayed the "file not found" message before.
  5. Experiment with other supported file types by entering the file URLs. Notice that when you enter a URL outside of your application’s domain, a pop-up window appears—this is Central as it requests permission to access a specific domain—a good security measure.

Additional Resources


About the author

Geoffrey, born in 1982, learned about computers and the internet at an early age from his father (a computer engineer). Tinkering with electronics, drawing cartoons, and "making things" were some of his early hobbies. He boasts thirteen years of perfect school attendance and exceptional math and science skills. He is currently completing a two year graphic design/web design certification course.

A Macromedia aficionado and Team Macromedia member for Central, Geoffrey has been working with Macromedia products for the better part of the past five years. Within that time, he has learned and mastered Macromedia Flash, Dreamweaver, and ColdFusion; he also has experience with Contribute, HomeSite, ColdFusion Studio, Flash Communication Server, Flash Remoting, Fireworks, Freehand, Adobe Illustrator and Adobe Photoshop. He has extensive experience with Macromedia Flash ActionScript and Flash development practices, which he displays through his contributions at FlashKit.com.